package com.ruoyi.biz.imported.strategy;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.lang.Validator;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.google.common.collect.Lists;
import com.ruoyi.biz.imported.vo.ReqVO;
import com.ruoyi.biz.letter.domain.BizMayorHotline;
import com.ruoyi.biz.letter.mapper.BizMayorHotlineMapper;
import com.ruoyi.biz.letter.mapper.BizProvinceLetterMapper;
import com.ruoyi.biz.letter.util.SysDeptUtil;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.utils.sign.Md5Utils;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Objects;
import java.util.Optional;

/**
 * @author Fei.Cong
 * @date 2024-07-18 15:08
 */
@Slf4j
@Service
public class HotlineStrategy implements ImportedStrategy {

    @Autowired
    private BizMayorHotlineMapper bizMayorHotlineMapper;

    @SneakyThrows
    @Override
    public String importHandleData(ReqVO reqVO) {

        ExcelUtil<BizMayorHotline> util = new ExcelUtil<BizMayorHotline>(BizMayorHotline.class);
        List<BizMayorHotline> citySheet1List = util.importEasyExcel(reqVO.getFile().getInputStream(), 0, 1);

        if (CollectionUtil.isEmpty(citySheet1List)) {
            throw new ServiceException("导入数据不能为空！");
        }
        int successNum = 0;
        int failureNum = 0;
        int existNum = 0;
        StringBuilder msg = new StringBuilder();

        if (!reqVO.isUpdateSupport()) {
            List<BizMayorHotline> letterList = Lists.newArrayList();
            List<Long> ids = Lists.newArrayList();
            for (BizMayorHotline cityLetter : citySheet1List) {
                try {
                    String serialNumber = Md5Utils.hash(cityLetter.getLetterNumber() + cityLetter.getLetterTitle() + cityLetter.getLetterPhone() + cityLetter.getLetterTime());
                    BizMayorHotline entity = bizMayorHotlineMapper.selectOne(new LambdaQueryWrapper<BizMayorHotline>()
                            .eq(BizMayorHotline::getMd5, serialNumber));
                    if (Objects.nonNull(entity)) {
                        if (Objects.nonNull(entity.getPCategoryId()) || Objects.nonNull(entity.getSCategoryId())) {
                            failureNum++;
                            msg.append("<br/>" + failureNum + "、信访件编号 " + cityLetter.getLetterNumber() + " <font color='green'>已分类</font>");
                            continue;
                        } else {
                            ids.add(entity.getId());
                            existNum++;
                            msg.append("<br/>" + existNum + "、信访件编号 " + cityLetter.getLetterNumber() + " <font color='blue'>已更新</font>");
                        }
                    } else {
                        successNum++;
                        msg.append("<br/>" + successNum + "、信访件编号 " + cityLetter.getLetterNumber() + " <font color='green'>已导入</font>");
                    }
                    cityLetter.setMd5(serialNumber);
                    cityLetter.setOwnerArea(StrUtil.isNotBlank(cityLetter.getOwnerArea()) ? SysDeptUtil.getDeptId("", cityLetter.getOwnerArea()) + "" : "");
                    cityLetter.setPCategoryId(Optional.ofNullable(cityLetter.getFirstCategoryName()).map(Long::new).orElse(null));
                    cityLetter.setSCategoryId(Optional.ofNullable(cityLetter.getSecondCategoryName()).map(Long::new).orElse(null));
                    cityLetter.setAcceptDept(cityLetter.getHandleDept());
                    letterList.add(cityLetter);
                } catch (Exception e) {
                    failureNum++;
                    String emsg = "<br/>" + failureNum + "、信访件编号 " + cityLetter.getLetterNumber() + " 导入失败：";
                    msg.append(emsg + e.getMessage());
                    log.error(emsg, e);
                }
            }
            if (CollectionUtil.isNotEmpty(ids)) {
                bizMayorHotlineMapper.deleteByIds(ids);
            }
            bizMayorHotlineMapper.insert(letterList);
        }

        msg.insert(0, "操作成功！成功 " + successNum + " 条，更新 " + existNum + " 条，失败 " + failureNum + " 条，数据如下：");

        return msg.toString();
    }
}
